﻿using System;
using System.Web.Mvc;

namespace Sencha.Direct
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
	public class AllowJsonPAttribute : FilterAttribute, IResultFilter
	{
		private string m_callbackParamName;

		public string CallbackParameterName { get { return m_callbackParamName; } }

		public AllowJsonPAttribute()
		{
			m_callbackParamName = "callback";
		}

		public AllowJsonPAttribute(string callbackParameterName)
		{
			if (string.IsNullOrEmpty(callbackParameterName))
				throw new ArgumentNullOrEmptyException("callbackParameterName");

			m_callbackParamName = callbackParameterName;
		}

		public static bool IsDefined(System.Reflection.ICustomAttributeProvider attrs)
		{
			if (attrs == null)
				throw new ArgumentNullException("attrs");

			var foundAttrs = attrs.GetCustomAttributes(typeof(AllowJsonPAttribute), true);
			return (foundAttrs != null && foundAttrs.Length > 0);
		}

		#region IResultFilter Members

		public void OnResultExecuted(ResultExecutedContext filterContext)
		{

		}

		public void OnResultExecuting(ResultExecutingContext filterContext)
		{
			if (filterContext.Result is DirectJsonResult)
			{
				var callbackFunction = filterContext.HttpContext.Request.QueryString[this.CallbackParameterName];
				if (string.IsNullOrEmpty(callbackFunction))
					return;

				var directResponse = (filterContext.Result as DirectJsonResult);
				directResponse.IsJsonP = true;
				directResponse.CallbackFunctionName = callbackFunction;
			}
		}

		#endregion
	}
}
